package com.will.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.will.server.mapper.UserMapper;
import com.will.server.pojo.User;
import com.will.server.pojo.UserData;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {
    /**
     * Auther sun
     * DATE 2023/1/15 0:17
     * VERSION 1.0
     */
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Value("${jwt.salt}")
    private String salt;

    @PostMapping("/register")
    public String register(@RequestBody String json) {
        logger.info("开始注册");
        Gson gson = new Gson();
        Map map = gson.fromJson(json, Map.class);
        String name = (String)map.get("name");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        User user = userMapper.selectOne(queryWrapper);
        if(user != null) {
            return "用户名重复";
        }
        String password = (String)map.get("password");
        User user1 = new User(null, name, null, password, null);
        userMapper.insert(user1);
        return "注册成功";
    }

    @PostMapping("/login")
    public String login(@RequestBody String json) {
        logger.info("开始登录");
        Gson gson = new Gson();
        Map map = gson.fromJson(json, Map.class);
        String name = (String)map.get("name");
        String password = (String)map.get("password");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        queryWrapper.eq("password", password);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null) {
            return "密码错误";
        }
        String toJson = gson.toJson(user);
        redisTemplate.opsForValue().set("user:" + name, toJson);
        return "登录成功";
    }

    @GetMapping("/login/getUserInfo")
    public ResponseEntity<Void> getUserInfo(String code, HttpServletResponse response) {

        String appId = "wx1082ee136e2ed1f4";
        String secret = "7bae384fee0ce217553193787ce71f34";
        String grant_type = "authorization_code";

        String url = "https://api.weixin.qq.com/sns/jscode2session";
        url = url + "?appid="+appId+"&secret="+secret+"&js_code="+code+"&grant_type="+grant_type;
        String loginResponse = restTemplate.getForObject(url, String.class);
        Gson gson = new Gson();
        Map map = gson.fromJson(loginResponse, Map.class);
        //每个用户一个openId
        String openid = (String)map.get("openid");
        //每个用户一个map
        Map userMap = redisTemplate.opsForHash().entries("users:" + DigestUtils.md5Hex(openid));
        if(userMap.isEmpty()) {
            UserData userData = new UserData();
            userData.setOpenId(DigestUtils.md5Hex(openid));
            userData.setMyCards("");
            userData.setMyFoot("");
            userData.setMyCollect("");
            userData.setMyScore(100);
            Map<String, Object> newUserMap = new HashMap<>();
            newUserMap.put("key", gson.toJson(userData));
            redisTemplate.opsForHash().putAll("users:" + DigestUtils.md5Hex(openid), newUserMap);
        }
        //为用户生成Token
        Map<String, Object> claims = new HashMap<>();
        claims.put("openid", DigestUtils.md5Hex(openid));
        //加密（生成Token） HS256：加密方法 salt：盐噪声
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, salt)
                //.setExpiration(new Date(System.currentTimeMillis() + 1 * 1000))
                .compact();
        response.setHeader("x-auth-token", token);
        response.setHeader("openid", DigestUtils.md5Hex(openid));
        return ResponseEntity.ok().build();
    }
}
